import os
import subprocess
import sys

def check_venv_installed():
    """Check if python3-venv is installed, if not, prompt to install it."""
    try:
        subprocess.run(['python3', '-m', 'venv', '--help'], check=True)
    except subprocess.CalledProcessError:
        print("python3-venv is not installed. Please install it using:")
        print("sudo apt install python3-venv")
        sys.exit(1)

def create_virtual_env(env_name='venv', requirements_file='requirements.txt'):
    """Create a virtual environment and install dependencies from requirements.txt."""
    print(f"Creating virtual environment '{env_name}'...")
    result = subprocess.run([sys.executable, '-m', 'venv', env_name])

    if result.returncode != 0:
        print("Failed to create virtual environment. Please check your Python installation.")
        return

    # Determine the pip path based on the operating system
    pip_path = os.path.join(env_name, 'Scripts', 'pip') if os.name == 'nt' else os.path.join(env_name, 'bin', 'pip')

    # Check if pip exists
    if not os.path.isfile(pip_path):
        print(f"Warning: 'pip' not found in the virtual environment. Please check your Python installation.")
        return

    if not os.path.isfile(requirements_file):
        print(f"Warning: '{requirements_file}' not found. Skipping dependency installation.")
        return

    print("Installing dependencies from requirements.txt...")
    install_result = subprocess.run([
        pip_path,
        'install',
        '-r', requirements_file,
        '-i', 'https://pypi.tuna.tsinghua.edu.cn/simple'
    ])
    if install_result.returncode != 0:
        print("Failed to install dependencies. Please check your requirements.txt file.")

if __name__ == "__main__":
    # Check if python3-venv is installed
    check_venv_installed()

    # Get the environment name from command line arguments, or use 'venv' as default
    env_name = sys.argv[1] if len(sys.argv) > 1 else 'venv'
    create_virtual_env(env_name)
